import { NextResponse } from 'next/server'
import { VmsCopy } from '@/types/Model'
import prisma from '@/lib/prisma'
import { getUser } from '@/lib/authUtils'

export async function PUT(req: Request): Promise<Response> {
  try {
    const userid = await getUser(req)
    if (!userid) {
      return NextResponse.json(
        { error: '未授权或登录信息过期，请登录' },
        { status: 401 }
      )
    }
    if (userid instanceof NextResponse) {
      return userid
    }

    const copies: VmsCopy[] = await req.json()

    // 批量更新文案的pxh
    const updatePromises = copies.map(async (copy) => {
      await prisma.vms_copy.update({
        where: { id: copy.id },
        data: {
          status: copy.status,
          pxh: copy.pxh
        }
      })
    })

    await Promise.all(updatePromises)

    return NextResponse.json({ message: '文案顺序更新成功' }, { status: 200 })
  } catch (error) {
    console.error('Error updating copy order:', error)
    return NextResponse.json(
      { error: '文案顺序更新失败' },
      { status: 500 }
    )
  }
}
